﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Quebec.Phone.Animations
{
	public class PositionAnimation : AnimationBase
	{
		public static TimeSpan DefaultDuration = TimeSpan.FromMilliseconds(250);

		public PositionAnimation(double left, double top)
			: this(left, top, DefaultDuration)
		{
		}

		public PositionAnimation(double left, double top, TimeSpan duration)
		{
			Left = left;
			Top = top;
			Duration = duration;
		}

		public double Left
		{
			get;
			private set;
		}

		public double Top
		{
			get;
			private set;
		}

		public TimeSpan Duration
		{
			get;
			private set;
		}

		protected override void ApplyValues(Storyboard storyboard)
		{
			if (storyboard == null)
				throw new ArgumentNullException("storyboard");

			var leftAnimation = storyboard.Children[0] as DoubleAnimationUsingKeyFrames;
			var topAnimation = storyboard.Children[1] as DoubleAnimationUsingKeyFrames;

			leftAnimation.KeyFrames[0].Value = Left;
			leftAnimation.KeyFrames[0].KeyTime = KeyTime.FromTimeSpan(Duration);
			topAnimation.KeyFrames[0].Value = Top;
			topAnimation.KeyFrames[0].KeyTime = KeyTime.FromTimeSpan(Duration);
		}

		protected override Storyboard CreateStoryboard()
		{
			var storyboard = new Storyboard();

			var leftAnimation = new DoubleAnimationUsingKeyFrames();
			var topAnimation = new DoubleAnimationUsingKeyFrames();

			Storyboard.SetTargetProperty(leftAnimation, new PropertyPath("(Canvas.Left)"));
			Storyboard.SetTargetProperty(topAnimation, new PropertyPath("(Canvas.Top)"));

			storyboard.Children.Add(leftAnimation);
			storyboard.Children.Add(topAnimation);

			leftAnimation.KeyFrames.Add(new SplineDoubleKeyFrame()
			{
				KeySpline = new KeySpline()
				{
					ControlPoint1 = new Point(0.528, 0),
					ControlPoint2 = new Point(0.142, 0.847)
				}
			});

			topAnimation.KeyFrames.Add(new SplineDoubleKeyFrame()
			{
				KeySpline = new KeySpline()
				{
					ControlPoint1 = new Point(0.528, 0),
					ControlPoint2 = new Point(0.142, 0.847)
				}
			});

			return storyboard;
		}
	}
}
